<?php
namespace app\admin\controller;
use ETaobao\Factory;
class Tbkcat extends Base {
    public $tbk = null;
    public function __construct(){
      parent::__construct();
      $config = [
          'appkey' => '23545895',
          'secretKey' => '07831869794dba604792dd4b297be9f9',
          'format' => 'json',
          'sandbox' => false,
      ];
      $app = Factory::Tbk($config);
      $this->tbk = $app;
    }
    //列表
    public function lists() {
        if (is_post()) {
            $d = $this->post;
            $map = [];
            if ($d['keyword'] != '') {
                $map[] = ['and', 'cat_title', 'like', "%{$d['keyword']}%"];
            }
            if ($d['status'] != '') {
                $map[] = ['and', 'status', '=', $d['status']];
            }
            $w = where($map);
            $rs = $this->db->query("select * from tbk_cat $w[0] order by id desc" . limit($d['page'], $d['limit']), $w[1], '', true);
            if ($rs) {
                foreach ($rs[0] as $key => $val) {
                    $rs[0][$key]['create_time'] = date('Y-m-d H:i', $val['create_time']);
                }
                suc($rs[0], $rs[1]);
            } else {
                suc([], 0);
            }
        }
        return $this->fetch();
    }

    //添加
    public function add() {
        if (is_post()) {
            $d = $this->post;
            $rule = [
              'cat_title'=>'require',
              'adzone_id'=>'require',
            ];
            $msg = [];
            check($rule,$msg,$d);
            unset($d['file']);
            $d['create_time'] = time();
            if(!isset($d['favorites_id'])){
              err('请选择选品库');
            }else{
              $d['favorites_id'] = implode(",",$d['favorites_id']);
            }
            $id = $this->db->insert('tbk_cat', $d);
            if ($id) {
                m('Attachment','xcom')->imgSure('tbk_cat',$id,$d);
                cookie('js_msg', '添加成功');
                cookie('js_function', 'preload');
                return suc();
            } else {
                err('添加失败');
            }
        }
        $param = [
           'fields' => "favorites_title,favorites_id,type",
           'page_size'=>15,
           'page_no'=>1,
        ];
        $res = $this->tbk->uatm->getFavorites($param);
        $res = json_encode($res);
        $res = json_decode($res,true);
        $xpk = $res['results']['tbk_favorites'];
        $this->fetch(['xpk'=>$xpk]);
    }

    //编辑
    public function edit() {
        if (is_post()) {
            $d = $this->post;
            $rule = [
              'cat_title'=>'require',
              'adzone_id'=>'require',
            ];
            $msg = [];
            check($rule,$msg,$d);
            unset($d['file']);
            $d['create_time'] = time();
            if(!isset($d['favorites_id'])){
              err('请选择选品库');
            }else{
              $d['favorites_id'] = implode(",",$d['favorites_id']);
            }
            $id = $this->db->update('tbk_cat', $d);
            if ($id) {
                m('Attachment','xcom')->imgSure('tbk_cat',$id,$d);
                cookie('js_msg', '编辑成功');
                cookie('js_function', 'preload');
                return suc();
            } else {
                err('编辑失败');
            }
        }
        $param = [
           'fields' => "favorites_title,favorites_id,type",
           'page_size'=>15,
           'page_no'=>1,
        ];
        $res = $this->tbk->uatm->getFavorites($param);
        $res = json_encode($res);
        $res = json_decode($res,true);
        $xpk = $res['results']['tbk_favorites'];
        $id = $this->get('id');
        $info = $this->db->query("select * from tbk_cat where id=?", [$id], 1);
        $this->fetch(['xpk'=>$xpk,'info'=>$info]);
    }

    //同步选品库的产品
    public function tongbu(){
      $id = $this->get('id');
      $page_no = $this->get('page_no',1);
      if($id==0){
         $first_data = $this->db->query("select favorites_id from tbk_item_temp order by id asc",[],1);
         if(!$first_data) t('同步数据完成');
         //删除原数据
         $this->db->query("delete from tbk_item where favorites_id=?",[$first_data['favorites_id']]);
         $rs = $this->db->query("select * from tbk_item_temp where favorites_id=? order by id asc limit 100",[$first_data['favorites_id']]);
         $ids  = [];
         $data = [];
         foreach($rs as $v){
           $ids[]  = $v['id'];
           $data[] = $v;
         }
         $rs = $this->db->insertAll('tbk_item',$data);
         if($ids) $this->db->query("delete from tbk_item_temp where id in (".implode(',',$ids).")");
         js_url('',0.1);
      }
      e('插入远程数据');
      $info = $this->db->find('tbk_cat',$id);
      $favorites_ids = explode(",",$info['favorites_id']);
      $temp = [];
      foreach($favorites_ids as $v){
          $param = [
             'fields' => "num_iid,title,pict_url,small_images,zk_final_price_wap,status,coupon_click_url,coupon_info,coupon_remain_count,tk_rate,coupon_start_time,coupon_end_time,user_type,type,volume,reserve_price,category",
             'platform'=>2,
             'adzone_id'=>$info['adzone_id'],
             'favorites_id'=>$v,
             'page_size'=>50,
             'page_no'=>$page_no,
          ];
          $res = $this->tbk->uatm->getItemFavorites($param);
          $res = json_encode($res);
          $res = json_decode($res,true);
          if(isset($res['results']['uatm_tbk_item'])){
            foreach($res['results']['uatm_tbk_item'] as $key => $val){
              $res['results']['uatm_tbk_item'][$key]['favorites_id'] = $v;
            }
            $temp = array_merge($temp,$res['results']['uatm_tbk_item']);
          }
      }

      $data = [];
      foreach($temp as $k => $v){
        //去掉没有券的商品,没有相册图,失效的
        if(!isset($temp[$k]['coupon_click_url']) || !isset($v['small_images']) || !isset($v['small_images']['string']) || $v['status']==0){
          continue;
        }
        $d = [
          'tbk_cat_id' => $id,
          'user_id' => 1,
          'num_iid' => $v['num_iid'],
          'title' => $v['title'],
          'pict_url' => $v['pict_url'],
          'small_images' => implode(',',$v['small_images']['string']),
          'zk_final_price_wap' => $v['zk_final_price_wap'],
          'coupon_click_url' => $v['coupon_click_url'],
          'coupon_info' => $v['coupon_info'],
          'coupon_remain_count' => $v['coupon_remain_count'],
          'tk_rate' => $v['tk_rate'],
          'coupon_start_time' => $v['coupon_start_time'],
          'coupon_end_time' => $v['coupon_end_time'],
          'user_type' => $v['user_type'],
          'type' => $v['type'],
          'status' => $v['status'],
          'volume' => $v['volume'],
          'reserve_price' => $v['reserve_price'],
          'favorites_id' => $v['favorites_id'],
          'category' => $v['category']
        ];
        $data[] = $d;
      }
      if($data){
        $rs = $this->db->insertAll('tbk_item_temp',$data);
        r(url('tbkcat/tongbu',['id'=>$id,'page_no'=>$page_no+1]));
      }else{
        r(url('tbkcat/tongbu',['id'=>0]));
      }
    }

}
